/*
 * @Author: zeki mini
 * @Date: 2021-05-11 09:40:03
 * @LastEditors: 汪滔
 * @LastEditTime: 2021-07-02 13:45:51
 * @Description: 隐私协议版本检测相关
 */

import { Dimensions, Platform, NativeModules } from 'react-native';
import { msg } from '@/common';
import user from '@/api/user';
import homeApi from '@/api/home';
import baseConfig from '@/config/baseConfig';

const { terminalCode } = baseConfig;
// 字符串版本号比较
export function versionStringCompare(preVersion = '', lastVersion = '') {
  let sources = preVersion.split('.');
  let dests = lastVersion.split('.');
  let maxL = Math.max(sources.length, dests.length);
  let result = 0;
  for (let i = 0; i < maxL; i++) {
    let preValue = sources.length > i ? sources[i] : 0;
    let preNum = isNaN(Number(preValue)) ? preValue.charCodeAt() : Number(preValue);
    let lastValue = dests.length > i ? dests[i] : 0;
    let lastNum = isNaN(Number(lastValue)) ? lastValue.charCodeAt() : Number(lastValue);
    if (preNum < lastNum) {
      result = -1;
      break;
    } else if (preNum > lastNum) {
      result = 1;
      break;
    }
  }
  return result;
}

// 隐私协议版本号对比
export function compareDealVersion(checkUserDealArray, articlesList, callback) {
  let isShow = false;
  checkUserDealArray.map((item) => {
    articlesList.map((articItem) => {
      if ((versionStringCompare(item.versionNum, articItem.versionNum)) && (item.dealCode == articItem.contentCode)) {
        isShow = true;
      }
    });
  });
  callback && callback(isShow);
}

// 校验隐私协议签署状态
export function checkUserAgreement(mobile, articlesList, callback) {
  console.log('🚀🚀🚀wimi======>>>mobile, articlesList', mobile, articlesList);
  let dealCodeArray = [];
  articlesList.map((item) => {
    dealCodeArray.push(item.code);
  });
  user.checkUserDeal({ mobile, dealCode: dealCodeArray, terminalCode }).then(res => {
    if (res.success && res.data) {
      // 对比是否需要弹窗
      compareDealVersion(res.data, articlesList, (isShowFirstLoad) => {
        callback && callback(isShowFirstLoad);
      });
    } else {
      msg.emit('app:tip', { text: res.msg ? res.msg : '连接服务器失败!' });
    }
  }).catch(() => {
    msg.emit('app:tip', { text: '连接服务器失败!!' });
  });
}

export function getAgreementByArray(params, callback) {
  // ['agreement','privacyAgreement','PerInfoAgreement']
  homeApi.getContentInfoListByCode(params).then(res => {
    if (res.success) {
      callback && callback(res.data);
    } else {
      msg.emit('app:tip', { text: res.msg ? res.msg : '连接服务器失败' });
    }
  }).catch(() => {
    msg.emit('app:tip', { text: '连接服务器失败' });
  });
}
